package com.core.gui.dialog;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.ObjectInputStream.GetField;
import java.sql.Connection;
import java.util.ArrayList;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.core.dao.DAOException;
import com.core.dao.impl.DBUtil;
import com.core.entities.Contact;
import com.core.entities.Work;
import com.core.gui.helper.UserInfo;
import com.core.gui.helper.model.ContactTableModel;

public class ContactSearch extends JDialog {



	private final JPanel contentPanel = new JPanel();
	private final JLabel lblPleaseSelectHow = new JLabel(
			"Please select How you want search about contact ?.");
	private final JRadioButton firstNameRdbtn = new JRadioButton(" First Name");
	private final JRadioButton lastNameRdbtn = new JRadioButton("Last Name");
	private final JRadioButton cityRdbtn = new JRadioButton("City");
	private final JRadioButton facebookRdbtn = new JRadioButton("Facebook");
	private final JRadioButton emailRdbtn = new JRadioButton("E-Mail");
	private final JRadioButton mobilePhoneRdbtn = new JRadioButton(
			"Mobile Phone");
	private final JLabel lblEnterValueOf = new JLabel(
			"Enter value of what you select:");
	private final JTextField entryTextField = new JTextField();
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private final JLabel countryLabel = new JLabel("Country : ");
	private final JComboBox countryComboBox = new JComboBox(UserInfo
			.getInstance().getService().getCountrySrv().getCountriesNames()
			.toArray());
	private final JLabel stateLabel = new JLabel("State :");
	private final JComboBox stateComboBox = new JComboBox(UserInfo
			.getInstance().getService().getStateSrv()
			.getStateByCountry(countryComboBox.getSelectedItem().toString())
			.toArray());
	private final JLabel cityLabel = new JLabel("City :");
	private final JComboBox cityComboBox = new JComboBox(UserInfo.getInstance()
			.getService().getCitySrv()
			.getCities(stateComboBox.getSelectedItem().toString()).toArray());
	private final JPanel entryPanel = new JPanel();
	private final JPanel cityPanel = new JPanel();
	private final JScrollPane scrollPane = new JScrollPane();
	private final JTable searchTable = new JTable(new ContactTableModel(
			new ArrayList<Contact>()));
	private final JButton searchButton = new JButton("Search");
	private final JRadioButton catagoryRdbtn = new JRadioButton("Catagory");
	private final JPanel catagoryPanel = new JPanel();
	private final JLabel lblCatagory = new JLabel("Catagory :");
	private final JComboBox catagoryComboBox = new JComboBox(UserInfo
			.getInstance().getService().getCatagorySrv().getCatagoryNames()
			.toArray());
	private final JPopupMenu optionPopupMenu = new JPopupMenu();
	private final JMenuItem editMntm = new JMenuItem("Edit");
	private final JMenuItem deleteMntm = new JMenuItem("Delete");
	private final JLabel testLabel = new JLabel("New label");
	private final JButton btnNewButton = new JButton("New button");

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			ContactSearch dialog = new ContactSearch();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */

	public ContactSearch() {
		setBounds(100, 100, 626, 523);
		getContentPane().setLayout(new BorderLayout());
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		{
			lblPleaseSelectHow.setBounds(10, 11, 251, 14);
			contentPanel.add(lblPleaseSelectHow);
		}
		{
			buttonGroup.add(firstNameRdbtn);
			firstNameRdbtn.setBounds(10, 32, 79, 23);
			contentPanel.add(firstNameRdbtn);

		}
		{
			buttonGroup.add(lastNameRdbtn);
			lastNameRdbtn.setBounds(91, 32, 75, 23);
			contentPanel.add(lastNameRdbtn);
		}
		{
			buttonGroup.add(mobilePhoneRdbtn);
			mobilePhoneRdbtn.setBounds(343, 32, 89, 23);
			contentPanel.add(mobilePhoneRdbtn);
		}
		{
			buttonGroup.add(cityRdbtn);
			buttonGroup.add(catagoryRdbtn);

			cityRdbtn.setBounds(168, 32, 45, 23);
			contentPanel.add(cityRdbtn);
		}
		{
			buttonGroup.add(facebookRdbtn);
			facebookRdbtn.setBounds(215, 32, 71, 23);
			contentPanel.add(facebookRdbtn);
		}
		{
			countryComboBox.setBounds(63, 11, 100, 20);
			countryComboBox.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {

					String countryName = ((JComboBox) e.getSource())
							.getSelectedItem().toString();

					stateComboBox.removeAllItems();
					for (String item : UserInfo.getInstance().getService()
							.getStateSrv().getStateByCountry(countryName))
						stateComboBox.addItem(item);
					repaint();
				}
			});
		}
		{
			stateComboBox.setBounds(204, 11, 100, 20);
			stateComboBox.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					String stateName = ((JComboBox) e.getSource())
							.getSelectedItem().toString();

					cityComboBox.removeAllItems();
					for (String item : UserInfo.getInstance().getService()
							.getCitySrv().getCities(stateName))
						cityComboBox.addItem(item);
					repaint();
				}
			});
		}
		{
			buttonGroup.add(emailRdbtn);
			emailRdbtn.setBounds(288, 32, 53, 23);
			contentPanel.add(emailRdbtn);
		}
		catagoryComboBox.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				((JComboBox) e.getSource()).getSelectedItem().toString();

			}
		});

		cityPanel.setBounds(101, 62, 439, 42);
		contentPanel.add(cityPanel);
		cityPanel.setLayout(null);
		cityPanel.setVisible(false);
		countryLabel.setBounds(10, 14, 49, 14);
		cityPanel.add(countryLabel);
		cityPanel.add(countryComboBox);
		stateLabel.setBounds(167, 14, 33, 14);
		cityPanel.add(stateLabel);
		cityPanel.add(stateComboBox);
		cityLabel.setBounds(308, 14, 26, 14);
		cityPanel.add(cityLabel);
		cityComboBox.setBounds(338, 11, 89, 20);
		cityPanel.add(cityComboBox);
		{
			entryPanel.setBounds(10, 62, 445, 49);
			contentPanel.add(entryPanel);
			entryPanel.setLayout(null);
			entryPanel.setVisible(true);
		}

		lblEnterValueOf.setBounds(-1, 18, 151, 14);
		entryPanel.add(lblEnterValueOf);
		entryTextField.setEnabled(true);
		entryTextField.setBounds(160, 10, 275, 30);
		entryPanel.add(entryTextField);
		entryTextField.setColumns(10);

		searchButton.setBounds(246, 115, 103, 23);
		contentPanel.add(searchButton);
		searchButton.setActionCommand("OK");
		getRootPane().setDefaultButton(searchButton);

		{
			scrollPane.setAutoscrolls(true);
			scrollPane.setBounds(10, 150, 590, 291);
			contentPanel.add(scrollPane);
		}
		addPopup(scrollPane, optionPopupMenu);
		optionPopupMenu.setBounds(0, 0, 137, 28);
		{
	
			optionPopupMenu.add(editMntm);
		}
		{
			optionPopupMenu.add(deleteMntm);
		}
		{
			scrollPane.setViewportView(searchTable);
			searchTable.setAutoscrolls(true);

		}
		{
			catagoryRdbtn.setBounds(434, 32, 109, 23);
			contentPanel.add(catagoryRdbtn);
		}
		{
			catagoryPanel.setBounds(213, 70, 219, 34);
			contentPanel.add(catagoryPanel);
		}
		catagoryPanel.setLayout(null);
		{
			lblCatagory.setBounds(10, 11, 52, 14);
			catagoryPanel.add(lblCatagory);
		}
		{
			catagoryComboBox.setBounds(64, 8, 145, 20);
			catagoryPanel.add(catagoryComboBox);
		}
		{
			testLabel.setBounds(531, 11, 46, 14);
			contentPanel.add(testLabel);
		}
		{
		
			btnNewButton.setBounds(428, 115, 89, 23);
			contentPanel.add(btnNewButton);
		}
//		searchTable.getSelectionModel().addListSelectionListener(new RowListener());
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {

						dispose();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}

		this.addMouseListener(new MouseListener() {

			@Override
			public void mouseReleased(MouseEvent mv) {
				if (mv.isPopupTrigger()) {
					optionPopupMenu.show(mv.getComponent(), mv.getX(),
							mv.getY());
				}
			}

			@Override
			public void mousePressed(MouseEvent mv) {
				if (mv.isPopupTrigger()) {
					optionPopupMenu.show(mv.getComponent(), mv.getX(),
							mv.getY());
				}
			}

			@Override
			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseEntered(MouseEvent arg0) {
			}

			@Override
			public void mouseClicked(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		setItemListener();
		setActionListener();
		
		editMntm.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
//				AddContact addContact = new AddContact();
				prepareDataToUi(getDataFromTable());
			//	getDataFromTable();
			//	new AddContact().setVisible(true);
				
//				testLabel.setText(getDataFromTable().getFirstName())
//				addContact.firstNameTextField.setText(getDataFromTable().getFirstName());
//				addContact.setVisible(true);

			}
		});

		

	}
	private void prepareDataToUi(Contact contact){
		AddContact addContact = new AddContact();
	
		/// set contact fields data 
		addContact.firstNameTextField.setText(getDataFromTable().getFirstName());
		addContact.secondNameTextField.setText(getDataFromTable().getSecondName());
		addContact.thirdNameTextField.setText(getDataFromTable().getThirdName());
		addContact.lastNameTextField.setText(getDataFromTable().getLastName());
		addContact.addressTextArea.setText(getDataFromTable().getAddress());
		addContact.cityComboBox.setSelectedItem(getDataFromTable().getCity().getName());
		addContact.landPhoneTextField.setText(getDataFromTable().getLandPhone());
		addContact.mobilePhoneTextField.setText(getDataFromTable().getMobileNumber());
		addContact.emailTextField.setText(getDataFromTable().getEmail());
		addContact.websiteTextField.setText(getDataFromTable().getWebsite());
		addContact.jobTextField.setText(getDataFromTable().getJob());
		
//		int contactOnlineAccountId = getDataFromTable().getOnlineAccountId();
//		getDataFromTable().setOnlineAccountId(contactOnlineAccountId);
//		
//		
//		int contactWorkId = getDataFromTable().getWorkId();
//		getDataFromTable().setWorkId(contactWorkId);
	
		/// set contact online account  fields data
		addContact.facebookTextField.setText(getDataFromTable().getOnlineAccount().getFacebook());
		addContact.twitterTextField.setText(getDataFromTable().getOnlineAccount().getTwitter());
		addContact.googleTextField.setText(getDataFromTable().getOnlineAccount().getGoogle());
		
		/// set work fields data
		addContact.companyTextField.setText(getWorkDataFromTable().getCompnyName());
		addContact.workLandPhoneTextField.setText(getWorkDataFromTable().getLandPhone());
		addContact.workMobilePhoneTextField.setText(getWorkDataFromTable().getMobilePhone());
		addContact.workEmailTextField.setText(getWorkDataFromTable().getEmail());
		addContact.workWebsiteTextField.setText(getWorkDataFromTable().getWebsite());
		
//		int workOnlineAccountId = getWorkDataFromTable().getOnlineAccountId();
//		getWorkDataFromTable().setOnlineAccountId(workOnlineAccountId);
		
		///set work online fields data
		addContact.workFacebookTextField.setText(getWorkDataFromTable().getOnlineAccount().getFacebook());
		addContact.workGoogleTextField.setText(getWorkDataFromTable().getOnlineAccount().getGoogle());
		addContact.workTwitterTextField.setText(getWorkDataFromTable().getOnlineAccount().getTwitter());
		addContact.workCityComboBox.setSelectedItem(getWorkDataFromTable().getCity().getName());
		
		addContact.setVisible(true);
		addContact.okButton.setVisible(false);
		addContact.updateButton.setVisible(true);

		
	}
    public void updateContact() {
    	AddContact addContact = new AddContact();
    	int row = searchTable.getSelectedRow();
        int choise = JOptionPane.showConfirmDialog(null, 
                                                   "Are you sure you want to update this patient?", "Confirmation",JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
        if (choise == JOptionPane.OK_OPTION) {
            try {
                int contactId = Integer.parseInt(searchTable.getModel().getValueAt(row, 0).toString());
                if(contactId >= 0){
                    Contact oldDate = getDataFromTable();
                    Contact newDate = addContact.prepareContactObject();
                    newDate.setId(contactId);
                    if(newDate != null){
                        UserInfo.getInstance().getService().getContactSrv().getContactDAO().update(newDate);
                      
                    }   
                }
            } catch (DAOException e) {
e.printStackTrace();
            }
        }
    }
	private Contact getDataFromTable(){
        int row = searchTable.getSelectedRow();
        int col = searchTable.getSelectedColumn();

        int contactId = Integer.parseInt(searchTable.getModel().getValueAt(row, 0).toString());
        Contact contact = new Contact();
        try{
        	contact = UserInfo.getInstance().getService().getContactSrv().getContactDAO().getByPrimaryKey(contactId);
        }catch(DAOException e){
        	e.printStackTrace();
        }
        return contact;
	}
	
	private Work getWorkDataFromTable(){
		int contactId = getDataFromTable().getWorkId();
		Work work = new Work();
		try{
			work = UserInfo.getInstance().getService().getWorkSrv().getWorkDAO().getByPrimaryKey(contactId);
		}catch(DAOException e){
			e.printStackTrace();
		}
		return work;
	}
//    private class RowListener implements ListSelectionListener {
//        public void valueChanged(ListSelectionEvent event) {
//            if (event.getValueIsAdjusting()) {
//                return;
//            }
//            if(event.getFirstIndex()>=0){
//                prepareDataToUi(getDataFromTable());
////                updateButton.setEnabled(true);
////                deleteButton.setEnabled(true);
////                historyButton.setEnabled(true);
//            }else{
////                updateButton.setEnabled(false);
////                deleteButton.setEnabled(false);
////                historyButton.setEnabled(false);
//            }
//        }
//    }

	private void setItemListener() {

		firstNameRdbtn.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent e) {
				cityPanel.setVisible(false);
				entryPanel.setVisible(true);
				catagoryPanel.setVisible(false);
				entryTextField.setEnabled(true);

			}
		});

		lastNameRdbtn.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent e) {
				cityPanel.setVisible(false);
				entryPanel.setVisible(true);
				catagoryPanel.setVisible(false);
				entryTextField.setEnabled(true);

			}
		});

		cityRdbtn.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent e) {
				e.getItemSelectable();
				if (cityRdbtn.isSelected()) {
					entryPanel.setVisible(false);
					catagoryPanel.setVisible(false);
					cityPanel.setVisible(true);
				}
			}
		});
		emailRdbtn.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent e) {
				cityPanel.setVisible(false);
				entryPanel.setVisible(true);
				catagoryPanel.setVisible(false);
				entryTextField.setEnabled(true);
			}
		});
		facebookRdbtn.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent e) {
				cityPanel.setVisible(false);
				entryPanel.setVisible(true);
				catagoryPanel.setVisible(false);
				entryTextField.setEnabled(true);
			}
		});
		mobilePhoneRdbtn.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent e) {
				cityPanel.setVisible(false);
				entryPanel.setVisible(true);
				catagoryPanel.setVisible(false);

				entryTextField.setEnabled(true);
			}
		});

		catagoryRdbtn.addItemListener(new ItemListener() {

			public void itemStateChanged(ItemEvent e) {
				e.getItemSelectable();
				if (catagoryRdbtn.isSelected()) {
					cityPanel.setVisible(false);
					entryPanel.setVisible(false);
					catagoryPanel.setVisible(true);
				}
			}
		});

	}

	private void setActionListener() {

		searchButton.addActionListener(new ActionListener() {
			// Contact contact ;
			Connection conn = DBUtil.getConnection();

			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (firstNameRdbtn.isSelected()) {

					searchTable.setModel(new ContactTableModel(UserInfo
							.getInstance().getService().getContactSrv()
							.getContactByFirstName(entryTextField.getText())));

				} else if (lastNameRdbtn.isSelected()) {
					searchTable.setModel(new ContactTableModel(UserInfo
							.getInstance().getService().getContactSrv()
							.getContactByLastName(entryTextField.getText())));

				} else if (cityRdbtn.isSelected()) {
					searchTable
							.setModel(new ContactTableModel(UserInfo
									.getInstance()
									.getService()
									.getContactSrv()
									.getContactByCityId(
											cityComboBox.getSelectedItem()
													.toString())));
				} else if (emailRdbtn.isSelected()) {
					searchTable.setModel(new ContactTableModel(UserInfo
							.getInstance().getService().getContactSrv()
							.getContactByEmail(entryTextField.getText())));
				} else if (mobilePhoneRdbtn.isSelected()) {
					searchTable.setModel(new ContactTableModel(UserInfo
							.getInstance().getService().getContactSrv()
							.getContactByMobilePhone(entryTextField.getText())));

				} else if (facebookRdbtn.isSelected()) {
					searchTable.setModel(new ContactTableModel(
							UserInfo.getInstance()
									.getService()
									.getContactSrv()
									.getContactByOnlineAccount(
											entryTextField.getText())));
				} else if (catagoryRdbtn.isSelected()) {
					searchTable.setModel(new ContactTableModel(UserInfo
							.getInstance()
							.getService()
							.getContactSrv()
							.getContactByCatagoryId(
									catagoryComboBox.getSelectedItem()
											.toString())));
				}
			}
		});

	}

	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}

			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}

			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
}
